import 'dart:math';

import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:webview_flutter_wkwebview/webview_flutter_wkwebview.dart';
import 'package:event_bus/event_bus.dart';

import '../base/javascript_channel.dart';
import '../test_web_controller_util.dart';

class TestShareWebControllerPage extends StatefulWidget {
  static bool showRedPadding = true;

  final bool? shouldHideNavBar;
  final String? url;

  final WebViewController? webController;
  final void Function(WebViewController controller)? onWebViewCreated;

  final bool? allowsInlineMediaPlayback;
  final Set<PlaybackMediaTypes>? mediaTypesRequiringUserAction;

  const TestShareWebControllerPage({
    Key? key,
    this.shouldHideNavBar = false,
    required this.url,
    this.webController,
    this.onWebViewCreated,
    this.allowsInlineMediaPlayback,
    this.mediaTypesRequiringUserAction,
  }) : super(key: key);

  @override
  _TestShareWebControllerPageState createState() =>
      _TestShareWebControllerPageState();
}

class _TestShareWebControllerPageState extends State<TestShareWebControllerPage>
    with WidgetsBindingObserver, RouteAware {
  String? _title;
  late WebViewController _controller;
  bool _showLoading = false;

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);

    // EventBusUtil.eventBus.fire(ShareWebControllerShowStateEvent(show: true));

    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);

    if (widget.webController != null) {
      _controller = widget.webController!;
    } else {
      _controller = defaultController;
      widget.onWebViewCreated?.call(_controller);
      _addJs();
      _loadRequest();
    }

    EventBusUtil.eventBus
        .on<ShareWebControllerShowStateEvent>()
        .listen((event) async {
      bool show = event.show;
      onRefresh();
    });
  }

  onRefresh() {
    if (mounted) {
      setState(() {
        // _showLoading = true;
        _controller = widget.webController!;
      });
    }
  }

  WebViewController get defaultController {
    PlatformWebViewControllerCreationParams params;
    if (WebViewPlatform.instance is WebKitWebViewPlatform) {
      params = WebKitWebViewControllerCreationParams(
        allowsInlineMediaPlayback: widget.allowsInlineMediaPlayback ?? true,
        mediaTypesRequiringUserAction: widget.mediaTypesRequiringUserAction ??
            const <PlaybackMediaTypes>{},
      );
    } else {
      params = const PlatformWebViewControllerCreationParams();
    }

    return WebViewController.fromPlatformCreationParams(params)
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(const Color(0xfff1f1f1))
      ..setNavigationDelegate(
        NavigationDelegate(
          onPageStarted: (String url) {
            if (mounted) {
              setState(() {
                _showLoading = true;
              });
            }
          },
          onPageFinished: (String url) {
            // _controller.getTitle().then((title) {
            //   if (mounted) {
            //   setState(() {
            //     _title =  title;
            //   });
            // }
            // });
            if (mounted) {
              setState(() {
                _showLoading = false;
              });
            }
          },
          onProgress: (int progress) {
            // _progressValue = progress / 100;
            // ToastUtil.showMessage('$progress%');

            if (mounted) setState(() {});
          },
          onWebResourceError: (WebResourceError error) async {
            _controller.getTitle().then((title) {});
            // _onErrorInnerHTML();
            //webview页面加载失败log
          },
        ),
      );
  }

  _addJs() {
    Set<JavascriptChannel> javascriptChannels = {
      /// 跳转到app指定页面_Name
      JavascriptChannel(
        name: "h5CallBridgeAction_showAppToast",
        onMessageReceived: (JavaScriptMessage message) {
          // Map map = json.decode(message.message);
          // String pageName = map["pageName"];
          // Map<String, dynamic>? pageParams = map["pageParams"];
          // RouteManager.pushPage(null, pageName, arguments: pageParams);
          List<String> uids = ["1475332557208702976", "234054", "495073"];
          var random = Random(); // 创建随机数生成器
          int randomNumber = random.nextInt(uids.length); // 生成0到99之间的随机整数

          String uid = uids[randomNumber];

          // Navigator.push(context, MaterialPageRoute(
          //   builder: (context) {
          //     return TestWebViewAppPage(flag: uid);
          //   },
          // ));
          // RouteManager.pushPage(
          //   null,
          //   RouteNames.spaceUserPage,
          //   arguments: {
          //     'id': uid,
          //   },
          // );
        },
      ),
    };

    for (var channel in javascriptChannels) {
      _controller.addJavaScriptChannel(
        channel.name ?? "unkonw",
        onMessageReceived: channel.onMessageReceived,
      );
    }
  }

  _loadRequest() {
    _controller.loadRequest(Uri.parse(widget.url!));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // resizeToAvoidBottomInset: false,
      // appBar: QuickAppBar(
      //   context,
      //   title: _title,
      //   actions: [
      //     ThemeBGButton(
      //       title: "刷新",
      //       bgColorType: ThemeBGType.blue,
      //       onPressed: () {
      //         onRefresh();
      //       },
      //     ),
      //   ],
      // ),
      body: Column(
        children: [
          _renderWebView(),
        ],
      ),
    );
  }

  _renderWebView() {
    return Expanded(
      // WillPopScope拦截手势返回
      child: Stack(
        fit: StackFit.expand,
        children: [
          Container(
            color: TestShareWebControllerPage.showRedPadding
                ? Colors.red
                : Colors.white,
            padding: TestShareWebControllerPage.showRedPadding
                ? const EdgeInsets.only(
                    left: 10, right: 10, top: 10, bottom: 10)
                : EdgeInsets.zero,
            child: WebViewWidget(controller: _controller),
          ),
          if (_showLoading) positionedLoadingView,
        ],
      ),
    );
  }

  Widget get positionedLoadingView {
    return Positioned(
      top: 0,
      bottom: 200,
      left: 0,
      right: 0,
      child: Container(
        // color: Colors.white,
        alignment: Alignment.center,
        child: const SizedBox(
          height: 30,
          width: 30,
          child: CircularProgressIndicator(
            strokeWidth: 3,
            valueColor: AlwaysStoppedAnimation(Color(0xFFE67D4F)),
          ),
        ),
      ),
    );
  }
}
